package com.wash.shoes.domain.order;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.wash.shoes.common.enums.JdEnum;
import com.wash.shoes.common.enums.OrderStatusEnum;
import com.wash.shoes.domain.dy.request.DyBookRequest;
import com.wash.shoes.domain.dy.request.DyRefundRequest;
import com.wash.shoes.domain.jd.JdOrderService;
import com.wash.shoes.domain.wx.WxPayProcess;
import com.wash.shoes.entity.CustomerCouponPo;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.entity.OrderTransportPo;
import com.wash.shoes.exception.WashException;
import com.wash.shoes.service.CustomerCouponService;
import com.wash.shoes.service.OrderService;
import com.wash.shoes.service.OrderTransportService;
import com.wash.shoes.service.RegionTransactionDetailService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * @author lijianguo
 * @Date 31/03/2025 10:36
 * 取消订单的信息
 **/
@Log4j2
@Component
public class CancelOrderComponent {

    @Resource
    OrderService orderService;

    @Autowired
    OrderTransportService orderTransportService;

    @Autowired
    JdOrderService jdOrderService;

    @Autowired
    private WxPayProcess wxPayProcess;

    @Resource
    RegionTransactionDetailService regionTransactionDetailService;

    @Autowired
    CustomerCouponService customerCouponService;

    @Resource
    DyBookRequest dyBookRequest;
    @Autowired
    private DyRefundRequest dyRefundRequest;


    public OrderPo process(OrderPo orderPo, String remark) {

        // 取消抖音的订单,已经小程序的订单
        String orderId = orderPo.getId();
        // 待支付和取鞋中的订单才可以取消
        // 没有付款的订单直接取消
        if (Objects.equals(orderPo.getStatus(), OrderStatusEnum.PRE_PAY.getStatus())) {
            orderPo.setStatus(OrderStatusEnum.CANCEL.getStatus());
            orderService.updateById(orderPo);
            // 优惠卷还原
            orderCouponRest(orderId);
        } else if (Objects.equals(orderPo.getStatus(), OrderStatusEnum.PICK_UP_SHOES.getStatus())) {
            // 已经有物流信息的订单
            List<OrderTransportPo> orderTransportPoList = orderTransportService.getByOrderId(orderId);

            if (!CollectionUtils.isEmpty(orderTransportPoList)) {
                Integer jdStatus = 0;
//                OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderId(orderId);
                OrderTransportPo po = Optional.of(orderTransportPoList)
                        .orElse(Collections.emptyList())
                        .stream()
                        .filter(p -> StringUtils.equals(p.getType(), "取鞋"))
                        .findFirst()
                        .orElse(null);
                if (Objects.nonNull(po)) {
                    //京东物流状态判断
                    jdStatus = Integer.parseInt(jdOrderService.jdLogisticsStatus(po));
                    log.info("美团取消京东物流状态为 {}", jdStatus);

                    if (jdStatus >= JdEnum.ORDER_YI_LS.getStatus()) {
                        throw new WashException("物流状态不正确，不能取消!!");
                    }
                } else {
                    throw new WashException("物流状态不正确，不能取消!!");

                }


                // 抖音的回掉 抖音这里还需要考虑一下,这里取消预约-0元退款-退款
                if ("3".equals(orderPo.getComeFrom())) {
                    //todo 需要把取消预约修改为协同退接口
                   /* String description = dyBookRequest.userCancelBookPo(orderPo);
                    if (!"success".equals(description)) {
                        throw new WashException("订单不能取消原因[" + description + "]");
                    }*/
                    com.alibaba.fastjson2.JSONObject jsonObject1 = dyRefundRequest.refund(orderPo);
                    log.info("抖音的取消订单信息:{},调用协同退: {}", orderPo.getId(), jsonObject1.toString());
                }

                // 已接单 已下发 就是100和390可以 取消
                if (Objects.equals(jdStatus, JdEnum.ORDER_YI_JD.getStatus()) || Objects.equals(jdStatus, JdEnum.ORDER_YI_XF.getStatus())) {
                    // 取消支付信息先
                    // 小程序的需要这里的取消, 抖音的不需要这个取消信息
                    String refundInfo = "success";
                    if (orderPo.getComeFrom().equals("4")) {
                        // 这个支付只针对小程序的处理
                        refundInfo = wxPayProcess.refund(orderPo);
                    }
                    log.info("微信支付的回退消息为 {}", refundInfo);
                    if ("success".equals(refundInfo)) {
                        // 取消物流信息
                        jdOrderService.cancelJdOrder(po.getWayBillCode());
                    } else {
                        throw new WashException(refundInfo);
                    }
                } else {
                    throw new WashException("物流已经揽收，不能被取消!!");
                }
            }
            orderPo.setStatus(OrderStatusEnum.CANCEL.getStatus());
            orderPo.setRemark(remark);
            orderService.updateById(orderPo);
            log.info("更新取消订单信息 {}", JSONObject.toJSONString(orderPo));
            // 优惠卷还原
            orderCouponRest(orderId);
        } else {
            throw new WashException("请联系管理员取消订单");
        }
        // 取消订单的佣金
        regionTransactionDetailService.cancelTransaction(orderId);
        return orderPo;
    }

    /**
     * 处理订单的的优惠卷
     *
     * @param orderId 订单的id
     */
    private void orderCouponRest(String orderId) {
        CustomerCouponPo customerCouponPo = customerCouponService.getByOrderId(orderId);
        if (customerCouponPo != null) {
            customerCouponPo.setStatus(0);
            customerCouponPo.setUserTime(null);
            customerCouponService.updateById(customerCouponPo);
        }
    }
}
